package com.lcm.weam.shiro;

import com.lcm.weam.entity.resp.ProfileResult;
import com.lcm.weam.entity.sys.User;
import com.lcm.weam.service.sys.UserService;
import org.apache.shiro.authc.*;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 自定义realm，构建自己的认证方法，使用密码登录
 *      AuthenticationToken : 就是token的实现
 *      AuthorizationInfo ： 携带类似于role1=user:add,user:update
 *      AuthenticationInfo： 携带类似于lcm=123456,role1
 */
public class UserRealm extends BaseRealm {

    @Autowired
    private UserService userService;

    @Override
    public void setName(String name){
        super.setName("userRealm");
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //认证方法
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String mobile = upToken.getUsername();
        String password = new String(upToken.getPassword());
        //查询用户
        User user = userService.selectByMobile(mobile);
        if (user != null && password.equals(user.getPassword())) {
            ProfileResult profileResult = new ProfileResult();
            profileResult.setUid(user.getUid());
            profileResult.setMobile(user.getMobile());
            profileResult.setUsername(user.getUsername());
            profileResult.setRole(user.getRole());
            profileResult.setEmail(user.getEmail());
            profileResult.setIsAuth(user.getIsAuth());
            //返回安全信息
            return new SimpleAuthenticationInfo(profileResult, user.getPassword(), this.getName());
        }
        //否则跳出异常
        return null;
    }
}
